import React from 'react';
import styles from './index.less';
import { message } from 'antd';
import { MicroAppWithMemoHistory, history, getDvaApp } from 'umi';
import {
  initGlobalState,
  addGlobalUncaughtErrorHandler,
  removeGlobalUncaughtErrorHandler,
} from 'qiankun';
import { getToken } from '@/utils/authority';
import { MICRO_CONFIG, SUB_MICRO_CONFIG } from './helper';
import jurisdiction from '@/utils/jurisdiction';
import renovate from '@/utils/renovate';
import { connect } from 'dva';
import { visitRecord } from '@/services/power';

@connect(({ user, global }) => ({
  curPath: user.curPath,
  menuCode: user.menuCode,
  eamGroup: user.eamGroup,
  appName: user.appName,
  theme: global.theme,
  currentThemeEnums: global.currentThemeEnums,
}))
export default class Micro extends React.Component {
  globalData = {};
  config = {};
  defaultOtherMicro = 'titanic';
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      menuCode: '',
      otherMicro: undefined,
      propsMenuCode: props.menuCode,
    };
    this.timer = null;
    this.isSubEam = props.route.path.includes('/Eam/SubMenu');
    this.isDynamicPage = props.route.path.includes('/DynamicPage');
  }
  componentDidMount() {
    this.timer = setTimeout(() => {
      this.onInit();
      addGlobalUncaughtErrorHandler(this.uncaughtErrorhandler);
    }, 500);
  }
  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
    removeGlobalUncaughtErrorHandler(this.uncaughtErrorhandler);
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.menuCode != prevState.propsMenuCode) {
      initGlobalState({}).setGlobalState({
        menuCode: nextProps.menuCode,
        curPath: nextProps.curPath?.split?.('/'),
      });
      return { propsMenuCode: nextProps.menuCode };
    }
    return null;
  }

  uncaughtErrorhandler = () => {};
  componentDidUpdate() {
    const microApp = MICRO_CONFIG?.[this.state.menuCode];
    if (microApp) {
      const { dispatch } = getDvaApp()._store;
      dispatch({
        type: 'global/update',
        payload: {
          isLargeScreenIn: microApp.name === 'screen',
        },
      });
    }
  }

  async onInit() {
    let { menuCode } = jurisdiction.getMenuItem(this.props.route.path) ?? {};
    if (this.isSubEam) {
      menuCode = 'EamSubMenu';
    }
    if (this.isDynamicPage) {
      menuCode = 'DynamicPage';
    }
    // menuCode = 'eamManager';
    this.config = MICRO_CONFIG?.[menuCode];
    if (!this.config) {
      return history.push('/404');
    }
    if (renovate.isFirst) {
      renovate.isFirst = false;
      if (this.config.name === 'eam') {
        this.defaultOtherMicro = 'configure';
      }
    }

    let token = await getToken();
    const causer = getDvaApp()?._store?.getState()?.user || {};
    this.globalData.token = token;
    this.globalData.curPath = this.props.curPath?.split?.('/');
    this.globalData.menuCode = this.isSubEam || this.isDynamicPage ? this.props.menuCode : menuCode;
    this.globalData.buttonPermissions = causer?.buttonPermissions || [];
    this.globalData.permissionsCodes = causer?.permissionsCodes || [];
    this.globalData.currentUser = causer?.currentUser || {};
    this.globalData.appMenuName = causer?.appName ?? '';
    this.globalData.eamGroup = this.props.eamGroup || [];
    this.globalData.themeEnums = this.props.currentThemeEnums || [];
    this.actions = initGlobalState({ type: '', data: '' });
    this.config.settings = {
      singular: true,
      sandbox: {
        strictStyleIsolation: this.config.isSandbox || false,
        experimentalStyleIsolation: this.config.isSandbox || false,
        loose: true,
      },
    };
    const that = this;
    this.actions.onGlobalStateChange((state, prev) => {
      // that.onHandleData(state);
    });
    this.setState({ isLoading: true, menuCode });
  }
  onSubMicroHandle(e) {
    const { type = '', data = {} } = e;
    switch (type) {
      case 'subMicroClose':
        this.setState({
          otherMicro: undefined,
        });
        break;
      default:
        break;
    }
  }
  onHandleData(e) {
    const { type = '', data = {}, callBack } = e;
    const { dispatch } = getDvaApp()._store;
    switch (type) {
      case 'changeEamSubMenu':
        dispatch({
          type: 'user/update',
          payload: { ...data },
          successCallback: callBack,
        });
        const menu = jurisdiction.PERMISSION_ARRAY.find(
          (n) => n.menuCode == data.menuCode && n.customApplicationName == this.props.appName,
        );
        if (!menu) {
          return message.warn('暂无权限');
        }
        visitRecord({
          firstMenuId: menu.firstMenuId,
          secondMenuId: menu.secondMenuId,
          customApplicationId: menu.customApplicationId,
        });

        history.push(`/Eam/SubMenu/${data.menuCode}`);
        break;
      case 'subCheckFeed':
        jurisdiction.onCheckFeed(data.menuCode);
        break;
      case 'subLogout':
        dispatch({ type: 'login/logout' });
        break;
      case 'subHistory':
        if (!data.path) {
          message.error('系统配置错误，请联系管理员！');
        } else if (data?.openType === 1) {
          let url = `${window.location.origin}/#/saas${data?.path}`;
          _.forEach(Object.keys(data?.params || {}), (_k, _i) => {
            url += `${_i === 0 ? '?' : '&'}${_k}=${data?.params[_k] || ''}`;
          });
          window.open(url);
        } else {
          const searchVal = Object.entries(data.params || {})
            .map(([key, val]) => `${key}=${val}`)
            .join('&');
          history.push({
            pathname: data.path,
            // query: { ...(data.params || {}) },
            search: searchVal ? '?' + searchVal : '',
            // query: { ...(data.params || {}) }, // ？可能会没有加上，用search主动加
          });
        }
        break;
      case 'subAmap':
        callBack && callBack();
        break;
      case 'subMicro':
        this.onInitSubMicro(data);
        break;
      case 'subRenovate':
        renovate = { ...renovate, ...(data ?? {}) };
        break;
      case 'changeTheme':
      // 具体的事情在layoutHeader里做
      // data?.theme &&
      //   dispatch({
      //     type: 'global/setTheme',
      //     payload: data.theme,
      //   });
      default:
        break;
    }
  }
  onInitSubMicro(params = {}) {
    const { abilityType = '', eventData = {} } = params;
    if (SUB_MICRO_CONFIG[abilityType]) {
      this.globalData.eventData = eventData;
      this.setState({
        otherMicro: SUB_MICRO_CONFIG[abilityType],
      });
    }
  }

  render() {
    if (!this?.config?.name) return null;
    let searchStr =
      this.props?.location?.search[0] === '?'
        ? this.props?.location?.search.substr(1)
        : this.props?.location?.search || '';
    return (
      <React.Fragment>
        <MicroAppWithMemoHistory
          {...this.config}
          url={`${this.config.url}${searchStr.length > 0 ? '?' : ''}${searchStr}`}
          location={this.props.location}
          onHandle={this.onHandleData.bind(this)}
          globalData={{
            ...this.globalData,
            theme: this.props.theme,
          }}
          prefetch={false}
          className={`${styles.micro_container} root_micro_container`}
        />
        {process.env.NODE_ENV === 'development' ? null : (
          <div style={{ height: '0px', overflow: 'hidden' }}>
            <MicroAppWithMemoHistory
              name={this.state.otherMicro ? this.state.otherMicro.name : this.defaultOtherMicro}
              url={this.state.otherMicro ? this.state.otherMicro.url : '/noe1'}
              globalData={{
                ...this.globalData,
                theme: this.props.theme,
              }}
              onHandle={this.onSubMicroHandle.bind(this)}
            />
          </div>
        )}
      </React.Fragment>
    );
  }
}
